package link.anyauto.j2m.executor;

import android.os.Handler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import link.anyauto.j2m.App;
import link.anyauto.j2m.ExecutorAct;

/**
 * Created by LYQ on 2016/5/12.
 */
public class ScheduledExecutorDemo {

    public ScheduledExecutorDemo(Handler uiHandler) {
        this.uiHandler = uiHandler;
    }

    public void start() {
        new Thread(){
            public void run() {
                scheduledPool(2);
            }
        }.start();
    }

    public void stop() {
        if(ses != null) {
            ses.shutdown();
            ses = null;
        }
    }

    void scheduledPool(int size) {
        ses = Executors.newScheduledThreadPool(size);

        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                timeConsumingJob("定时任务 1");
            }
        }, 1, 2, TimeUnit.SECONDS);

        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                timeConsumingJob("定时任务 2");
            }
        }, 2, 1, TimeUnit.SECONDS);
    }

    long timeConsumingJob(String name) {
        long sleep = 100 + (long)(Math.random() * 100);
        App.sleep(sleep);
        uiHandler.obtainMessage(ExecutorAct.MSG_LOG, "定时任务【" + name + "】在线程【" + Thread.currentThread().getName() + "】中即将执行完毕，消耗时间：" + sleep + "毫秒。").sendToTarget();
        return sleep;
    }

    Handler uiHandler;
    ScheduledExecutorService ses;
}
